module Fabriq
  module PluginPort
    extend self
    extend Fabriq::Logging

    attr_accessor :plugins

    def plugin_load_paths
      [File.expand_path("~") + "/.fabriq", Dir.pwd].collect do |base_path|
        Dir.glob("#{base_path}/plugins/*")
      end.flatten
    end

    def require_plugins
      debug "Plugin Load paths: #{plugin_load_paths}"

      plugin_load_paths.each do |plugin_base_dir|
        next unless File.exist?(plugin_base_dir)
        require_plugin_from_path plugin_base_dir
      end
    end

    def require_plugin_from_path(plugin_base_dir)
      plugin_name = plugin_base_dir.split("/").last
      base_file_path = File.join(plugin_base_dir, "lib", "#{plugin_name}.rb")
      if File.exist?(base_file_path)
        require base_file_path
      else
        error("Plugin: #{plugin_name} - Base file not found (#{base_file_path}")
      end
    end

    def register_plugin(klass, &config_block)
      @plugins ||= []

      plugin = klass.init

      if block_given? && plugin.respond_to?(:configurator)
        config_block.call(plugin.configurator)
      end

      invoke_plugin_callback(plugin, :registered)
      @plugins << plugin
    end

    def initialize_plugins
      @plugins.each do |plugin|
        invoke_plugin_callback(plugin, :initialized)
      end
    end

    private

    def invoke_plugin_callback(plugin, name, *args)
      plugin.send(name.to_sym, *args) if plugin.respond_to?(name.to_sym)
    end

    
  end
end